package com.jiegui.modules.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.jiegui.common.core.redis.RedisCache;
import com.jiegui.common.enums.UserRole;
import com.jiegui.common.exception.user.RRException;
import com.jiegui.common.model.WxChartModel;
import com.jiegui.common.model.WxUserInfo;
import com.jiegui.framework.utils.WechatUtils;
import com.jiegui.modules.utils.JwtUtils;
import com.jiegui.modules.utils.WXCore;
import com.jiegui.modules.wechat.model.LoginModel;
import com.jiegui.modules.wechat.model.UserDetailsModel;
import com.jiegui.modules.wechat.model.WxLoginModel;
import com.jiegui.system.service.ISystemConfigService;
import com.jiegui.wx.domain.WechatUser;
import com.jiegui.wx.service.IWechatUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: wuqicheng
 * @time: 09/12/2021 9:21 AM
 */
@Service
@Slf4j
public class WxChartServiceImpl implements WxChartService {
    @Resource
    ISystemConfigService systemConfigService;

    @Resource
    IWechatUserService wechatUserService;



    @Resource
    RedisCache redisCache;

    @Resource
    JwtUtils jwtUtils;

    @Override
    public WxLoginModel login(LoginModel dot, HttpServletRequest request) {
        String channel="applet";
        WxChartModel wxChartModel = systemConfigService.queryWxChart("WeChart");
        try {
            WxUserInfo wxUserInfo = WechatUtils.AppletsUserInfo(dot.getCode(), wxChartModel);
            if (StringUtils.isEmpty(wxUserInfo.getOpenid()) || StringUtils.isEmpty(wxUserInfo.getSessionKey())) {
                throw new RRException("小程序解密失败");
            }
            log.info("微信解密信息" + JSON.toJSONString(wxUserInfo));
            wechatUserService.refreshUnionidByOpenId(wxUserInfo.getOpenid(), wxUserInfo.getUnionid());

            WechatUser userEntity = wechatUserService.getOne(new LambdaQueryWrapper<WechatUser>().eq(WechatUser::getOpenId, wxUserInfo.getOpenid()));
            if (userEntity == null || StringUtils.isEmpty(userEntity.getOpenId())) {
                userEntity = new WechatUser();
                //保存小程序用户信息
                JSONObject json = WXCore.decryptData(dot.getEncryptedData(), wxUserInfo.getSessionKey(), dot.getIv());
                log.info("解密手机号"+json.toJSONString());
                userEntity.setPhone(json.getString("purePhoneNumber"));
                userEntity.setOpenId(wxUserInfo.getOpenid());
                userEntity.setRecord("登录");
                userEntity.setUnionid(wxUserInfo.getUnionid());
                userEntity.setChannel(channel);
                userEntity.setRegisterTime(new Date());
                if(StringUtils.isNotEmpty(userEntity.getPhone()))
                wechatUserService.save(userEntity);
            }
//            //判断有无账户
//            Account accountEntity = accountService.getOne(new QueryWrapper<Account>().
//                    eq("mobile", userEntity.getPhone()).
//                    eq("user_role", "MEMBER")
//                    .eq("channel",channel)
//            );
//            if (accountEntity == null && userEntity != null&&StringUtils.isNotEmpty(userEntity.getPhone())) {
//                accountEntity = new Account();
//                accountEntity.setAccName(userEntity.getNikeName());
//                accountEntity.setUserRole(UserRole.MEMBER.toString());
//                accountEntity.setAccStatus("0");
//                accountEntity.setMobile(userEntity.getPhone());
//                accountEntity.setChannel(channel);
//                accountService.insertAccount(accountEntity);
//            }

            //生成token
            String token = jwtUtils.generateToken(userEntity.getId());
            redisCache.setCacheObject(token, token,7,TimeUnit.DAYS);
            WxLoginModel info = new WxLoginModel();
            info.setToken(token);
            info.setOpenid(wxUserInfo.getOpenid());
            info.setAvatarUrl(userEntity.getUserImg());
            info.setNickName(userEntity.getNikeName());
           // info.setIsAuth(StringUtils.isBlank(userEntity.getUserImg()) ? "FALSE" : "TRUE");
            info.setPhone(userEntity.getPhone());
            request.getSession().setAttribute("user", userEntity);
            return info;
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            if (e instanceof RRException) {
                throw e;
            }
            throw new RRException("系统异常", 500);
        }
    }

//    @Override
//    public UserDetailsModel userDetails(WechatUser user) {
//        UserDetailsModel model=new UserDetailsModel();
//        Account account = accountService.getOne(new LambdaQueryWrapper<Account>().eq(Account::getMobile, user.getPhone()).eq(Account::getUserRole, UserRole.MEMBER).eq(Account::getChannel,"applet"));
//        model.setAccountNo(account.getAccountNo());
//        model.setBalance(account.getBalance());
//        model.setMobile(user.getPhone());
//        return model;
//    }

}
